import { useStores } from '@/stores';
import { Button, Checkbox, Modal } from 'antd';
import React, { Ref, useEffect, useImperativeHandle, useState } from 'react';

interface FilterConf {
  onRef: Ref<unknown> | undefined;
  data?: Array<any>;
  onSubmit?: (data: Array<any>) => void;
  type: FlawFilterType;
}
import './index.less';

import { Storage } from '@/utils/storage';
import { FlawFilterType } from '@/typings/global';
const CheckboxGroup = Checkbox.Group;

const FlawFilterPmp: React.FC = (props: FilterConf) => {
  const { sysMapStore, commonStore, lotStore } = useStores();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [checkAll, setCheckedAll] = useState({}); // 写一个方法处理传过来的prop属性

  const [checkedList, setCheckedList] = useState({});
  const [checkedStation, setCheckedStation] = useState(false);
  const [checkedAllLV1, setCheckedAllLV1] = useState(false);
  const [checkedAllLV2, setCheckedAllLV2] = useState(false);
  const [checkedAllLV3, setCheckedAllLV3] = useState(false);

  const [gobal, setGobal] = useState(commonStore.FlawTypePmpGobal);

  // 打开
  const showModal = () => {
    handleInitShow(props.type);
  };

  // 处理初始化显示
  const handleInitShow = type => {
    if (type == FlawFilterType.map) {
      const cacheData = Storage.get('map_checkedFlawType');
      if (!cacheData) {
        setCheckedList(gobal.defaultFlaw);
        setCheckedAllLV1(true);
        changeThreeVal(false); // 工位不选 lv2不选lv3不选
        setCheckedAll(gobal.fatherFlawFalse);
        setIsModalOpen(true);
        return;
      }
      setCheckedList(cacheData.checkedList);
      setCheckedAllLV1(cacheData.checkedAllLV1);
      setCheckedAllLV2(cacheData.checkedAllLV2);
      setCheckedAllLV3(cacheData.checkedAllLV3);
      setCheckedAll(cacheData.checkAll);
      setCheckedStation(cacheData.checkedStation);
      setIsModalOpen(true);
    }
    if (type == FlawFilterType.lotId) {
      const cacheData = Storage.get('lotId_checkedFlawType');
      if (!cacheData) {
        setCheckedList(gobal.defaultFlaw);
        setCheckedAllLV1(true);
        changeThreeVal(false); // 工位不选 lv2不选lv3不选
        setCheckedAll(gobal.fatherFlawFalse);
        setIsModalOpen(true);
        return;
      }
      setCheckedList(cacheData.checkedList);
      setCheckedAllLV1(cacheData.checkedAllLV1);
      setCheckedAllLV2(cacheData.checkedAllLV2);
      setCheckedAllLV3(cacheData.checkedAllLV3);
      setCheckedAll(cacheData.checkAll);
      setCheckedStation(cacheData.checkedStation);
      setIsModalOpen(true);
    }
  };

  // 缺陷筛选 确定提交
  const handleOk = () => {
    console.log('选中的缺陷:', checkedList);
    setIsModalOpen(false);
    let checkedFlawType = [] as number[];
    Object.keys(checkedList).forEach(key => {
      const item = checkedList[key];
      if (item.length) {
        checkedFlawType.push(...item);
      }
    });
    checkedFlawType = checkedFlawType.filter(v => v !== null && v !== undefined);
    if (props.type == FlawFilterType.map) {
      Storage.set('map_checkedFlawType', {
        checkedList: checkedList,
        checkedFlawType: checkedFlawType,
        checkedStation: checkedStation,
        checkedAllLV1: checkedAllLV1,
        checkedAllLV2: checkedAllLV2,
        checkedAllLV3: checkedAllLV3,
        checkAll: checkAll
      });
    }

    if (props.type == FlawFilterType.lotId) {
      Storage.set('lotId_checkedFlawType', {
        checkedList: checkedList,
        checkedFlawType: checkedFlawType,
        checkedStation: checkedStation,
        checkedAllLV1: checkedAllLV1,
        checkedAllLV2: checkedAllLV2,
        checkedAllLV3: checkedAllLV3,
        checkAll: checkAll
      });
    }
    // 给前制程选中的缺陷赋值

    if (props.type == FlawFilterType.map) {
      sysMapStore.changeCheckedFlawType(checkedFlawType); //综合Map页面的选中的缺陷
    }
    if (props.type == FlawFilterType.lotId) {
      lotStore.changeCheckedFlawType(checkedFlawType); // 卷详情选中的缺陷
    }
  };
  
  // 关闭对话框
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  useImperativeHandle(props.onRef, () => {
    return { showModal, handleCancel };
  });

  //   单独改变这个缺陷
  const onChange = (list: Array<number>, fatherId: number) => {
    // console.log('行——---单独改变这个缺陷', list, fatherId);
    setCheckedList(listOld => {
      let temp = { ...listOld };
      temp[fatherId] = list;
      return temp;
    });
    if (list.length !== gobal.sonFlawTrue[fatherId].length) {
      setCheckedAll(listOld => {
        let temp = { ...listOld } as any;
        temp[fatherId] = false;
        return temp;
      });
    }
    if (list.length == gobal.sonFlawTrue[fatherId].length) {
      setCheckedAll(listOld => {
        let temp = { ...listOld } as any;
        temp[fatherId] = true;
        return temp;
      });
    }
    handleIsCheckAllStation(fatherId, 'one', list);
    openAllLv123('LV1', fatherId, 'one', list);
    openAllLv123('LV2', fatherId, 'one', list);
    openAllLv123('LV3', fatherId, 'one', list);
  };

  //   是否选中所有工位
  const changeSelectdStation = e => {
    console.log('现在选中的工位', e.target.checked);
    setCheckedStation(e.target.checked);
    if (e.target.checked) {
      console.log(gobal.fatherFlawTrue);
      setCheckedAll(gobal.fatherFlawTrue);
      setCheckedList(gobal.sonFlawTrue);
      changeAllLV(true);
    } else {
      setCheckedAll(gobal.fatherFlawFalse);
      setCheckedList(gobal.sonFlawFalse);
      changeAllLV(false);
    }
  };

  // 同时改变3个值
  const changeAllLV = (isShow: boolean) => {
    setCheckedAllLV1(isShow);
    setCheckedAllLV2(isShow);
    setCheckedAllLV3(isShow);
  };

  // 同时改变3个值
  const changeThreeVal = (isShow: boolean) => {
    setCheckedStation(isShow);
    setCheckedAllLV2(isShow);
    setCheckedAllLV3(isShow);
  };

  //  是否选中所有Lv1
  const changeSelectdAllLV1 = e => {
    console.log('现在选中的LV1', e.target.checked);
    setCheckedAllLV1(e.target.checked);
    if (e.target.checked) {
      setCheckedList(listOld => {
        let temp = { ...listOld };
        [...Object.keys(temp)].forEach(key => {
          if (gobal.checkLV1[key]) {
            temp[key] = [...new Set([...temp[key], gobal.checkLV1[key]])];
          }
        });
        return temp;
      });
      openStationAll('LV1', true);
    } else {
      setCheckedList(listOld => {
        let temp = { ...listOld };
        [...Object.keys(temp)].forEach(key => {
          temp[key] = temp[key].filter(item => item !== gobal.checkLV1[key]);
        });
        return temp;
      });
      setCheckedAll(gobal.fatherFlawFalse);
      setCheckedStation(false);
    }
  };
  //  是否选中所有Lv2
  const changeSelectdAllLV2 = e => {
    console.log('现在选中的LV2', e.target.checked);
    setCheckedAllLV2(e.target.checked);
    if (e.target.checked) {
      setCheckedList(listOld => {
        let temp = { ...listOld };
        [...Object.keys(temp)].forEach(key => {
          temp[key] = [...new Set([...temp[key], gobal.checkLV2[key]])];
        });

        return temp;
      });
      openStationAll('LV2', true);
    } else {
      setCheckedList(listOld => {
        let temp = { ...listOld };
        [...Object.keys(temp)].forEach(key => {
          temp[key] = temp[key].filter(item => item !== gobal.checkLV2[key]);
        });
        return temp;
      });
      setCheckedAll(gobal.fatherFlawFalse);
      setCheckedStation(false);
    }
  };

  //  是否选中所有Lv3
  const changeSelectdAllLV3 = e => {
    console.log('现在选中的LV3', e.target.checked);
    setCheckedAllLV3(e.target.checked);
    if (e.target.checked) {
      setCheckedList(listOld => {
        let temp = { ...listOld };
        [...Object.keys(temp)].forEach(key => {
          temp[key] = [...new Set([...temp[key], gobal.checkLV3[key]])];
        });

        return temp;
      });
      openStationAll('LV3', true);
    } else {
      setCheckedList(listOld => {
        let temp = { ...listOld };
        [...Object.keys(temp)].forEach(key => {
          temp[key] = temp[key].filter(item => item !== gobal.checkLV3[key]);
        });
        return temp;
      });
      setCheckedAll(gobal.fatherFlawFalse);
      setCheckedStation(false);
    }
  };

  //   每行的全选按钮
  const onCheckAllChange = (e, fatherId) => {
    if (e.target.checked) {
      setCheckedAll(listOld => {
        let temp = { ...listOld } as any;
        temp[fatherId] = true;
        return temp;
      });
      setCheckedList(listOld => {
        let temp = { ...listOld };
        temp[fatherId] = gobal.sonFlawTrue[fatherId];
        return temp;
      });
      handleIsCheckAllStation(fatherId, 'more');
      openAllLv123('LV1', fatherId, 'more');
      openAllLv123('LV2', fatherId, 'more');
      openAllLv123('LV3', fatherId, 'more');
    } else {
      setCheckedAll(listOld => {
        let temp = { ...listOld } as any;
        temp[fatherId] = false;
        return temp;
      });
      setCheckedList(listOld => {
        let temp = { ...listOld };
        temp[fatherId] = [];
        return temp;
      });
    }
  };

  // 判断是否工位要全选：   行全选，单个全选
  const handleIsCheckAllStation = (fatherId: number, type: string, list?: Array<any>) => {
    let count = {};
    let temp = { ...checkedList };
    if (type == 'more') {
      temp[fatherId] = gobal.sonFlawTrue[fatherId];
    } else {
      temp[fatherId] = list;
    }

    Object.keys(temp).forEach(key => {
      count[key] = temp[key].length;
    });

    let isNotSame = true;
    Object.keys(count).forEach(key => {
      if (count[key] !== gobal.hasChildNum[key]) {
        isNotSame = false;
      }
    });
    setCheckedStation(isNotSame);
  };

  // 打开工位和父缺陷的全选
  const openStationAll = (key: string, isShow: boolean) => {
    if (key == 'LV1' && isShow && checkedAllLV2 && checkedAllLV3) {
      setCheckedAll(gobal.fatherFlawTrue);
      setCheckedStation(true);
    }
    if (key == 'LV2' && isShow && checkedAllLV1 && checkedAllLV3) {
      setCheckedAll(gobal.fatherFlawTrue);
      setCheckedStation(true);
    }
    if (key == 'LV3' && isShow && checkedAllLV1 && checkedAllLV2) {
      setCheckedAll(gobal.fatherFlawTrue);
      setCheckedStation(true);
    }
  };

  // 每行子缺陷的渲染列表
  const getChildFlaw = (obj: any) => {
    let option = [] as any;
    obj.children.forEach(item => {
      option.push({
        label: item.name,
        value: item.id
      });
    });
    return option;
  };

  // 当这一列的 LV1 | LV2 | LV3 全部勾选上了，就勾选表头的（LV1 | LV2 | LV3 ）全选
  const openAllLv123 = (key: string, fatherId: number, type: string, list?: Array<any>) => {
    let temp = { ...checkedList };
    if (type == 'more') {
      temp[fatherId] = gobal.sonFlawTrue[fatherId];
    } else {
      temp[fatherId] = list;
    }
    let isTrue = true;
    if (key == 'LV1') {
      Object.keys(gobal.checkLV1).forEach(key => {
        if (temp[key]) {
          if (!temp[key].includes(gobal.checkLV1[key])) {
            isTrue = false;
          }
        }
      });
    }
    if (key == 'LV2') {
      Object.keys(gobal.checkLV2).forEach(key => {
        if (temp[key]) {
          if (!temp[key].includes(gobal.checkLV2[key])) {
            isTrue = false;
          }
        }
      });
    }
    if (key == 'LV3') {
      Object.keys(gobal.checkLV3).forEach(key => {
        if (temp[key]) {
          if (!temp[key].includes(gobal.checkLV3[key])) {
            isTrue = false;
          }
        }
      });
    }
    if (isTrue) {
      if (key == 'LV1') {
        setCheckedAllLV1(isTrue);
      }

      if (key == 'LV2') {
        setCheckedAllLV2(isTrue);
      }

      if (key == 'LV3') {
        setCheckedAllLV3(isTrue);
      }
    }
  };

  return (
    <>
      <div>
        <Modal open={isModalOpen} onOk={handleOk} onCancel={handleCancel} className="flaw-filter">
          <div className="station table-title">
            <div className="station_name">{'工位列表'}</div>
            <div className="flaw_content">
              <div className="line_father_flaw">
                <div className="father_name">不良名称</div>
                <Checkbox onChange={changeSelectdStation} checked={checkedStation}>
                  工位全选
                </Checkbox>
                <Checkbox onChange={changeSelectdAllLV1} checked={checkedAllLV1}>
                  LV1
                </Checkbox>
                <Checkbox onChange={changeSelectdAllLV2} checked={checkedAllLV2}>
                  LV2
                </Checkbox>
                <Checkbox onChange={changeSelectdAllLV3} checked={checkedAllLV3}>
                  LV3
                </Checkbox>
                {/* <div>（整列全选）</div> */}
              </div>
            </div>
            <div></div>
          </div>
          <div className="child-flaw">
            {commonStore.FlawTypePmpConf.map((item: any, index) => (
              <div className="station">
                <div className="station_name">{item.name} </div>
                <div className="flaw_content" key={index}>
                  {item.children.map((val: any, inx) => (
                    <div className="line_father_flaw">
                      <div className="father_name">{val.name}</div>
                      <div className="checkbox">
                        <Checkbox
                          onChange={e => {
                            onCheckAllChange(e, val.id);
                          }}
                          checked={checkAll[val.id]}
                          style={{ marginRight: 30 }}
                        >
                          全选
                        </Checkbox>
                        <CheckboxGroup
                          // key={index + '_' + inx}
                          options={getChildFlaw(val)}
                          value={checkedList[val.id]}
                          onChange={list => {
                            onChange(list as any, val.id);
                          }}
                        />
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        </Modal>
      </div>
    </>
  );
};

export default FlawFilterPmp;
